package cn.tedu.charging.order.websocket;

import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import javax.websocket.*;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;
import java.util.Collection;
import java.util.concurrent.ConcurrentHashMap;

@Slf4j
@Component
@ServerEndpoint("/charing/{userId}")
public class ChargingWebSocketEndPoint {
    private static ConcurrentHashMap<Integer,Session> webSocketMap=new ConcurrentHashMap<>();
    public ChargingWebSocketEndPoint(){
        log.debug("WebChatSocketServer()");
    }
    @OnOpen
    public void onOpen(@PathParam("userId") Integer userId, Session session){
        webSocketMap.put(userId,session);
        log.debug("有新用户加入！当前连接数：{}",webSocketMap.size());
    }
    @OnClose
    public void onClose(Session session){
         log.debug("{}连接关闭，用户退出了！",session.getId());
    }
    @OnError
    public void onError(Session session,Throwable e){
        log.error("发生错误:{}",e.getMessage());
    }
    public static void sendAsyncMessage(Integer userId,String message){
        Session session=webSocketMap.get(userId);
        if(session!=null){
            session.getAsyncRemote().sendText(message);
        }
    }

}
